package com.homer.android.sdk.command.uart;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.homer.android.sdk.devcie.status.IEspStatusUart;
import com.homer.android.sdk.type.devcie.status.EspStatusUart;
import com.homer.android.sdk.type.net.HeaderPair;
import com.homer.android.sdk.type.user.builder.BEspUser;
import com.homer.iot.esptouch.base.api.EspBaseApiUtil;

public class EspCommandUartGetStatusInternet implements
		IEspCommandUartGetStatusInternet {

	private final static Logger log = Logger
			.getLogger(EspCommandUartGetStatusInternet.class);

	private IEspStatusUart getCurrentUartStatus(String deviceKey) {

		String headerKey = Authorization;
		String headerValue = Token + " " + deviceKey;

		HeaderPair header = new HeaderPair(headerKey, headerValue);

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("deviceNumber", deviceKey);
			jsonObject.put("userToken", BEspUser.getBuilder().getInstance()
					.getUserKey());
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		JSONObject jsonObjectResult = EspBaseApiUtil.Post(URL, jsonObject);

		int status = -1;
		try {
			if (jsonObjectResult != null)
				status = Integer.parseInt(jsonObjectResult.getString("status"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		if (status == HttpStatus.SC_OK) {			
			try {				
				int mIsLightOn = jsonObjectResult.getInt("isLightOn");
				int mIsDefenceOn = jsonObjectResult.getInt("isDefenceOn");
				String isOnline = jsonObjectResult.getString("online");
				IEspStatusUart statusUart = new EspStatusUart();
				statusUart.setIsLightOn(mIsLightOn == 1 ? 1 : 0);
				statusUart.setIsDefenceOn(mIsDefenceOn == 1 ? 1 : 0);
				statusUart.setIsOnline("online".equals(isOnline));
				statusUart.setIsSuccess(true);
				return statusUart;
			} catch (JSONException e) {
				IEspStatusUart statusUart = new EspStatusUart();
				
				statusUart.setIsSuccess(false);
				//e.printStackTrace();
				//return null;
				return statusUart;
			}
		} else {
			IEspStatusUart statusUart = new EspStatusUart();
			
			statusUart.setIsSuccess(false);
			return statusUart;
		}
	}

	@Override
	public IEspStatusUart doCommandUartGetStatusInternet(String deviceNumber) {
		IEspStatusUart result = getCurrentUartStatus(deviceNumber);
		log.debug(Thread.currentThread().toString()
				+ "##doCommandUartGetStatusInternet(deviceNumber=["
				+ deviceNumber + "]): " + result);
		return result;
	}

}
